package com.jiaoyou.baojian.activity;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.job.JobInfo;
import android.app.job.JobScheduler;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.ActionBar;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.jiaoyou.baojian.BaojianApplication;
import com.jiaoyou.baojian.MainActivity;
import com.jiaoyou.baojian.R;
import com.jiaoyou.baojian.agora.AgoraHelper;
import com.jiaoyou.baojian.constvalue.ConstValue;
import com.jiaoyou.baojian.daemon.service.VMBackgroundService;
import com.jiaoyou.baojian.daemon.service.VMCoreService;
import com.jiaoyou.baojian.daemon.service.VMDaemonJobService;
import com.jiaoyou.baojian.daemon.service.VMDaemonService;
import com.jiaoyou.baojian.daemon.service.VMForegroundService;
import com.jiaoyou.baojian.entity.GlobalSettingEntity;
import com.jiaoyou.baojian.http.Api;
import com.jiaoyou.baojian.http.BaofangCallback;
import com.jiaoyou.baojian.http.response.BaseResponse;
import com.jiaoyou.baojian.otto.Event;
import com.jiaoyou.baojian.utils.Utils;
import com.squareup.otto.Subscribe;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;

public class SplashActivity extends BaseActivity {

    private static final int UI_ANIMATION_DELAY = 300;
    private final Handler handler = new Handler();
    private final Runnable mHidePart2Runnable = new Runnable() {
        @SuppressLint("InlinedApi")
        @Override
        public void run() {
            bottom.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE
                    | View.SYSTEM_UI_FLAG_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
        }
    };
    private final Runnable mHideRunnable = new Runnable() {
        @Override
        public void run() {
            hide();
        }
    };
    @BindView(R.id.icon)
    ImageView icon;
    @BindView(R.id.bottom)
    LinearLayout bottom;
    @BindView(R.id.quit)
    TextView quit;

    private boolean globalSuccess = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        ButterKnife.bind(this);

        startCoreProcess();
        needOtto();
        handler.postDelayed(post, 1000);
        BaojianApplication.getInstance().pushService.clearNotifications();
        AgoraHelper.getInstance().setupSplashActivity(this);
    }
    private Runnable post = new Runnable() {
        @Override
        public void run() {
            next();
        }
    };

    private void next(){
        Api.getInstance().getGlobalSetting(new BaofangCallback<GlobalSettingEntity>(){
            @Override
            public void onFailure(Call<BaseResponse<GlobalSettingEntity>> call, Throwable t) {
                toast("网络错误，请稍后重试");
                finish();
                getHandler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        System.exit(0);
                    }
                }, 1000);
            }

            @Override
            public void onSuccess(GlobalSettingEntity globalSettingEntity) {
                globalSuccess = true;
                getACache().put("imageDomain", globalSettingEntity.domain.imgDomain);
                getACache().put("serverDomain", globalSettingEntity.domain.serverDomain);
                getACache().put("update", getGson().toJson(globalSettingEntity.Android));
                //获取服务器参数成功后，开始执行自动登录逻辑
                if(Utils.isLogin()) {
                    Log.e("next", "账号已经登录，执行自动登录流程");
                    final String account = getLoginResponse().user.id + "";
                    AgoraHelper.getInstance().agoraAPI.login(ConstValue.AGORA_APPID, account, Utils.getAgoraToken(account), 0, "");
//                    Api.getInstance().getLoginKey(account, new BaofangCallback<CallResponse>() {
//                        @Override
//                        public void onFailure(Call call, Throwable t) {
//                            toast("网络错误，请稍后重试");
//                            finish();
//                            getHandler().postDelayed(new Runnable() {
//                                @Override
//                                public void run() {
//                                    System.exit(0);
//                                }
//                            }, 1000);
//                        }
//
//                        @Override
//                        public void onSuccess(CallResponse res) {
//                            AgoraHelper.getInstance().agoraAPI.login(ConstValue.AGORA_APPID, account, res.agoraSignalingKey, 0, "");
//                        }
//                    });
                } else {
                    startActivity(LoginRegActivity.class);
                    finish();
                }
            }
        });
    }

    @Subscribe
    public void onEvent(String event){
        if(Event.AGORA_LOGIN_SUCCESS.equals(event)){
            //agora登录成功
            startActivity(MainActivity.class);
            BaojianApplication.getInstance().stayOnline();
            finish();
        } else if(Event.AGORA_LOGIN_ERROR.equals(event)){
            //agora登录失败
            toast("自动登录失败，请检查网络重试");
            finish();
        }
    }

    @Override
    public int getContentView() {
        return R.layout.activity_splash;
    }

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);

        delayedHide(100);
    }

    private void hide() {
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.hide();
        }

        handler.postDelayed(mHidePart2Runnable, UI_ANIMATION_DELAY);
    }

    private void delayedHide(int delayMillis) {
        handler.removeCallbacks(mHideRunnable);
        handler.postDelayed(mHideRunnable, delayMillis);
    }

    @OnClick(R.id.quit)
    public void onViewClicked() {
        handler.removeCallbacks(post);
        next();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode == KeyEvent.KEYCODE_BACK && event.equals(KeyEvent.ACTION_UP)){
            handler.removeCallbacks(post);
            finish();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 启动核心进程
     */
    private void startCoreProcess() {
        startService(new Intent(getApplicationContext(), VMCoreService.class));

        Intent foregroundIntent =
                new Intent(getApplicationContext(), VMForegroundService.class);
        startService(foregroundIntent);
        Intent daemonIntent =
                new Intent(getApplicationContext(), VMDaemonService.class);
        startService(daemonIntent);
        Intent backgroundIntent =
                new Intent(getApplicationContext(), VMBackgroundService.class);
        startService(backgroundIntent);

        startJobScheduler();
    }

    /**
     * 5.x以上系统启用 JobScheduler API 进行实现守护进程的唤醒操作
     */
    @TargetApi(Build.VERSION_CODES.LOLLIPOP) private void startJobScheduler() {
        int jobId = 1;
        JobInfo.Builder jobInfo =
                new JobInfo.Builder(jobId, new ComponentName(this, VMDaemonJobService.class));
        jobInfo.setPeriodic(10000);
        jobInfo.setPersisted(true);
        JobScheduler jobScheduler = (JobScheduler) getSystemService(Context.JOB_SCHEDULER_SERVICE);
        jobScheduler.schedule(jobInfo.build());
    }
}
